/**
 * 获取访问令牌接口测试用例
 *
 * Created by snowingsea on 2020/01/29.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));
const randomstring = require('randomstring');
const Administrator = require('./../../models/administrator');
const User = require('./../../models/user');
const common = require('./../common');
const uri = require('./uri');

/**
 * Export model definition object.
 */
module.exports = describe('/POST access-token.json', function () {
  const url = '/access-token.json';
  const administrator = new Administrator();
  let tester;
  const newUserIds = [];

  before(function (done) {
    administrator.createRandomTester()
      .then((user) => {
        tester = user;
        newUserIds.push(user.userId);
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => administrator.logout())
      .then(() => {
        done();
      })
      .catch(done);
  });

  // 正常请求
  it('it should GET access token', function (done) {
    chai.request(uri)
      .post(url)
      .send(tester.getPasswordGrantForm())
      .end((err, res) => {
        res.should.have.status(200);
        common.should.be.tokenMessage(res.body);
        done();
      });
  });

  // 用户名密码不匹配
  it('it should match the password', function (done) {
    const user = new User(tester.username, randomstring.generate(6));
    chai.request(uri)
      .post(url)
      .send(user.getPasswordGrantForm())
      .end((err, res) => {
        res.should.have.status(401);
        common.should.be.errorMessage(res.body);
        done();
      });
  });

  // 用户名不存在
  it('it should fail to get access token when the username is not exists', function (done) {
    let user;
    administrator.createRandomTester()
      .then((newUser) => {
        user = newUser;
        return administrator.removeUser(user.userId);
      })
      .then(() => {
        chai.request(uri)
          .post(url)
          .send(user.getPasswordGrantForm())
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 缺少参数
  Object.keys(new User('').getPasswordGrantForm()).forEach((key) => {
    it(`it should deny invalid request of missing "${key}"`, function (done) {
      const invalidQuery = tester.getPasswordGrantForm();
      delete invalidQuery[key];
      chai.request(uri)
        .post(url)
        .send(invalidQuery)
        .end((err, res) => {
          res.should.have.status(400);
          common.should.be.errorMessage(res.body);
          done();
        });
    });
  });
});
